package com.quyunshuo.module.home.activity.login

import android.text.TextUtils
import android.util.Log
import androidx.activity.viewModels
import androidx.core.widget.addTextChangedListener
import com.quyunshuo.androidbaseframemvvm.base.ktx.observeLiveData
import com.quyunshuo.androidbaseframemvvm.common.ext.click
import com.quyunshuo.androidbaseframemvvm.common.ui.BaseActivity
import com.quyunshuo.androidbaseframemvvm.network.bean.UserInfo
import com.quyunshuo.module.home.databinding.HomeFragmentLoginBinding
import com.tencent.bugly.proguard.u
import dagger.hilt.android.AndroidEntryPoint

/**
 * 首页
 *
 * @author Qu Yunshuo
 * @since 5/22/21 2:26 PM
 */
@AndroidEntryPoint
class LoginActivity : BaseActivity<HomeFragmentLoginBinding, LoginViewModel>() {

    private  val TAG = "LoginFragment"
    override val mViewModel by viewModels<LoginViewModel>()

    override fun createVB() = HomeFragmentLoginBinding.inflate(layoutInflater)

    override fun HomeFragmentLoginBinding.initView() {
        updateLoginState()

        //拿到name和password
        btnLogin.click{
            Log.d(TAG, "updateLoginState btnLogin: ")
            var username = etAccount.text.toString().trim()
            if (TextUtils.isEmpty(username)) {
                return@click
            }
            var password = etPassword.text.toString().trim()
            if (TextUtils.isEmpty(password)) {
                return@click
            }
            mViewModel.login(username,password)

        }

        etAccount.addTextChangedListener {_->
            updateLoginState()
        }
        etPassword.addTextChangedListener {_->
            updateLoginState()
        }

    }

    /**
     * 更新登录按钮状态
     */
    private fun updateLoginState() {
        val phone = mBinding.etAccount.text.toString()
        val phoneEnable = !phone.isNullOrEmpty()
        val password = mBinding.etPassword.text.toString()
        val passwordEnable = !password.isNullOrEmpty()
        Log.d(TAG, "updateLoginState: "+(phoneEnable && passwordEnable))
        mBinding.btnLogin.isEnabled = phoneEnable && passwordEnable
    }

    override fun initObserve() {
        observeLiveData(mViewModel.loginLiveData,::loginSuccess)
    }

    private fun loginSuccess(userInfo: UserInfo?) {
        finish()
    }

    override fun initRequestData() {
    }
}